package com.xxkk.utils;

import net.sf.json.JSONObject;

import java.io.*;
import java.util.Map;

/**
 * @author xxkk
 * @version 1.0.0
 * @title JsonUtils
 * @description ʕ•ᴥ•ʔ
 * @create 2023/12/4 15:52
 **/
public class JsonUtils {
    /**
     * 转成json字符串
     * */
    public static String toJson(Object object) {
        JSONObject jsonObject = JSONObject.fromObject(object);
        return jsonObject.toString();
    }
    public static String toJsonString(Object object) {
       return com.alibaba.fastjson.JSONObject.toJSONString(object);
    }
    public static JSONObject toJsonObj(String str) {
        return JSONObject.fromObject(str);
    }
    public static JSONObject toJsonObj(Object object) {
        return JSONObject.fromObject(object);
    }

    /* 读文件(json) */
    public static JSONObject parseFile(String path) {
        try {
            File file = new File(path);
            if (file.isFile() && file.exists() && file.canRead()) {
                String encoding = "GBK";
                InputStreamReader in;
                in = new InputStreamReader(new FileInputStream(file), encoding);
                BufferedReader bufferedReader = new BufferedReader(in);
                String lineTxt = "";
                StringBuilder sb = new StringBuilder(lineTxt);
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    if (!lineTxt.trim().equals("")) {
                        sb.append(lineTxt);
                    }
                }
                lineTxt = sb.toString();
                in.close();
                return JSONObject.fromObject(lineTxt);
            }else {
                System.out.println("找不到指定文件");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    /* 写入文件使用map */
    public static void updateFile(String path, Map<String, Object> newContent) {
        try {
            File file = new File(path);
            if (file.isFile() && file.canRead() && file.exists()) {
                BufferedWriter bw = new BufferedWriter(new FileWriter(path));
                // 一次写一行
                bw.write(toJson(newContent));
                bw.newLine(); // 换行用
                // 关闭流
                bw.close();
            }else {
                System.out.println("文件新建成功");
                file.createNewFile();
                BufferedWriter bw = new BufferedWriter(new FileWriter(path));
                // 一次写一行
                bw.write(toJson(newContent));
                bw.newLine(); // 换行用
                // 关闭流
                bw.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
